/**
 * Copyright 2013 Mani Selvaraj
 * <p/>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p/>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p/>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.uchedao.seller.http;

import android.text.TextUtils;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.HttpHeaderParser;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonSyntaxException;
import com.uchedao.seller.model.ResponseData;
import com.uchedao.seller.util.LogUtil;

import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

/**
 * Custom implementation of Request<T> class which converts the HttpResponse obtained to Java class objects.
 * Uses GSON library, to parse the response obtained.
 * Ref - JsonRequest<T>
 *
 * @author Mani Selvaraj
 */

public class PostRequest extends Request<JsonObject> {

    /**
     * Charset for request.
     */
    private static final String PROTOCOL_CHARSET = "utf-8";

    /**
     * Content type for request.
     */
    private static final String PROTOCOL_CONTENT_TYPE =
            String.format("application/json; charset=%s", PROTOCOL_CHARSET);

    private final Listener<JsonObject> mListener;

    private Gson mGson;

    private Map<String, String> mParams = new HashMap<String, String>();

    public PostRequest(Map<String, String> params, String action, Listener<JsonObject> listener,
                       ErrorListener errorListener) {
        super(Method.POST, action, errorListener);
        LogUtil.e("ACTION POST >>>>>>>>>>>>>>>>>>>>>>>>" + action);
        mGson = new Gson();
        mListener = listener;
        mParams = params;
    }

    @Override
    protected void deliverResponse(JsonObject response) {
        mListener.onResponse(response);
    }

    private Map<String, String> headers = new HashMap<String, String>();

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        return headers;
    }

    @Override
    protected Response<JsonObject> parseNetworkResponse(NetworkResponse response) {
        try {
            String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
            LogUtil.e("jsonString", ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n" + jsonString + "\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
            ResponseData responseData = mGson.fromJson(jsonString, ResponseData.class);
            String result = responseData.getError_code();
            if (TextUtils.isEmpty(result)) {
                LogUtil.e("resolverData", "返回结果不是合法的json格式");
                return Response.error(new VolleyError("返回结果不是合法的json格式"));
            }
            if ("0".equals(result)) {
                return Response.success(responseData.getData(),
                        HttpHeaderParser.parseCacheHeaders(response));
            } else {
                LogUtil.e("resolverData", responseData.getMessage());
//                if ("40002".equals(result)) {
//                    // token 过期处理 重新获取
////                    Toast.makeText(AuctionApplication.getAppContext()
////                            , AuctionApplication.getAppContext().getString(R.string.token_is_error)
////                            , Toast.LENGTH_SHORT).show();
////                    AppInfoManager.saveSTATE(false);
////                    // 重新启动主页，重新加载token
////                    Intent intent = new Intent(AuctionApplication.getAppContext(), WelComeActivity.class);
////                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
////                    AuctionApplication.getAppContext().startActivity(intent);
//
////                    AppInfoManager.syncToken();
////                    T.showNetworkError(UCheDaoApplication.getContext());
//                } else if ("40003".equals(result)) {
//                    //账号登录失效，重新登录
//                    UserInfoManager.saveSTATE(false);
//                    Intent intent = new Intent(UCheDaoApplication.getContext(), LoginActivity.class);
//                    UCheDaoApplication.getContext().startActivity(intent);
//                } else if ("80001".equals(result)) {
//                    responseData.setMessage(String.format("%s@%s", responseData.getError_code(), responseData.getMessage()));
//                }
                return Response.error(new VolleyError(responseData.getMessage()));
            }

        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (JsonSyntaxException je) {
            return Response.error(new ParseError(je));
        }
    }

    @Override
    public String getBodyContentType() {
        return PROTOCOL_CONTENT_TYPE;
    }


    @Override
    public byte[] getBody() {
        JSONObject jsonObject = new JSONObject(mParams);
        String mRequestBody = jsonObject.toString();
        LogUtil.e("POST>>>>>>>>"+mRequestBody);
        try {
            return mRequestBody == null ? null : mRequestBody.getBytes(PROTOCOL_CHARSET);
        } catch (UnsupportedEncodingException uee) {
            VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s",
                    mRequestBody, PROTOCOL_CHARSET);
            return null;
        }
    }
//    @Override
//    protected Map<String, String> getParams() throws AuthFailureError {
//        return mParams;
//    }
}
